﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.Communication.Adapters.File;
using PSE.Framework.Communication.Configuration.Adapters.File;
using PSE.Framework.Communication.Messages;
using PSE.Framework.Communication.Adapters;
using PSE.Framework.Communication.Messages.Adapters;

namespace PSE.Framework.Communication.Client.File
{
    /// <summary>
    /// Classe base dos clients de importação de arquivos
    /// </summary>
    /// <typeparam name="TOpenParameter">Tipo do parâmetro de abertura do processo</typeparam>
    public abstract class AsyncFileInputClient<TOpenParameter> : BaseInputClient<TOpenParameter>
        where TOpenParameter : class
    {
        #region Construtores
        /// <summary>
        /// Construtor padrão
        /// </summary>
        public AsyncFileInputClient()
        {
        }
        #endregion

        #region Adapter
        /// <summary>
        /// Adapter encapsulado pelo client
        /// </summary>
        protected new IAsyncFileInputAdapter Adapter
        {
            get { return (IAsyncFileInputAdapter)base.Adapter; }
        }
        #endregion

        #region FileStatus
        /// <summary>
        /// Status da importação do arquivo
        /// </summary>
        public FileStatus FileStatus
        {
            get
            {
                if (this.Adapter != null)
                {
                    switch (this.Adapter.StreamStatus)
                    {
                        case StreamStatus.Created:
                            return FileStatus.Created;
                        case StreamStatus.Opened:
                            return FileStatus.Opened;
                        case StreamStatus.Closed:
                            return FileStatus.Closed;
                        default:
                            return FileStatus.Created;
                    }
                }
                else
                {
                    return FileStatus.Created;
                }
            }
        }
        #endregion

        #region CreateProcess
        /// <summary>
        /// Cria o processo de comunicação
        /// </summary>
        /// <param name="process">Nome do processo</param>
        protected override void CreateProcess(string process, object parameter)
        {
            base.CreateProcess(process, parameter);

            this.Adapter.MessageReceived += new EventHandler<MessageEventArgs>(Adapter_MessageReceived);
            this.Adapter.MessageReceivedError += new EventHandler<MessageReceivedErrorEventArgs>(Adapter_MessageReceivedError);
            this.Adapter.StreamOpened += new EventHandler<StreamOpenedEventArgs>(Adapter_StreamOpened);
            this.Adapter.StreamClosed += new EventHandler<MessageEventArgs>(Adapter_StreamClosed);
            this.Adapter.StreamCanceled += new EventHandler<MessageEventArgs>(Adapter_StreamCanceled);
			this.Adapter.NewFileCreated += new EventHandler<FileCreatedEventArgs>(Adapter_NewFileCreated);
        }

		void Adapter_NewFileCreated(object sender, FileCreatedEventArgs e)
		{
			this.OnNewFileCreated(new FileCreatedEventArgs(e.FilePath));
		}

        #endregion

        #region Tratamento de Eventos
        /// <summary>
        /// Trata evento MessageReceived do processo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Adapter_MessageReceived(object sender, MessageEventArgs e)
        {
            this.OnRecordRead(new RecordEventArgs(e));
        }

        /// <summary>
        /// Trata evento MessageReceivedError do processo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Adapter_MessageReceivedError(object sender, MessageReceivedErrorEventArgs e)
        {
            this.OnRecordReadError((RecordReadErrorEventArgs)e);
        }

        /// <summary>
        /// Trata evento StreamOpened disparado pelo processo de comunicação
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Adapter_StreamOpened(object sender, StreamOpenedEventArgs e)
        {
            this.OnFileOpened(new FileOpenedEventArgs(e));
        }

        /// <summary>
        /// Trata evento StreamClosed disparado pelo processo de comunicação
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Adapter_StreamClosed(object sender, MessageEventArgs e)
        {
            this.OnFileClosed(new FileClosedEventArgs(e));
        }

        /// <summary>
        /// Trata evento StreamCanceled disparado pelo processo de comunicação
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Adapter_StreamCanceled(object sender, MessageEventArgs e)
        {
            this.OnFileCanceled(new FileCanceledEventArgs(e));
        }
        #endregion

        #region FileOpened
        /// <summary>
        /// Evento disparado quando o arquivo é aberto
        /// </summary>
        public event EventHandler<FileOpenedEventArgs> FileOpened;

        /// <summary>
        /// Dispara o evento FileOpened
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnFileOpened(FileOpenedEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (FileOpened != null)
            {
                FileOpened(this, e);
            }
        }
        #endregion

        #region FileClosed
        /// <summary>
        /// Evento disparado quando o arquivo é fechado
        /// </summary>
        public event EventHandler<FileClosedEventArgs> FileClosed;

        /// <summary>
        /// Dispara o evento FileClosed
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnFileClosed(FileClosedEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (FileClosed != null)
            {
                FileClosed(this, e);
            }
        }
        #endregion

        #region FileCanceled
        /// <summary>
        /// Evento disparado quando a importação do arquivo é cancelada
        /// </summary>
        public event EventHandler<FileCanceledEventArgs> FileCanceled;

        /// <summary>
        /// Dispara o evento FileCanceled
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnFileCanceled(FileCanceledEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (FileCanceled != null)
            {
                FileCanceled(this, e);
            }
        }
        #endregion

        #region CanImport
        /// <summary>
        /// Indica se o monitoramento da pasta de entrada fo iniciado
        /// </summary>
        public bool CanImport
        {
            get
            {
                if (this.Adapter != null)
                    return this.Adapter.CanReceive;
                else
                    return false;
            }
        }
        #endregion

        #region BeginImport
        /// <summary>
        /// Inicia o monitoramento da pasta de entrada
        /// </summary>
        public void BeginImport()
        {
            this.VerifyIsOpened();

            this.Adapter.BeginReceive();
        }

        /// <summary>
        /// Inicia o monitoramento da pasta de entrada
        /// </summary>
        /// <param name="parameter">Parâmetro de importação do arquivo</param>
        public void BeginImport(FileReceiveParameter parameter)
        {
            this.VerifyIsOpened();

            this.Adapter.BeginReceive(parameter);
        }
        #endregion

        #region EndImport
        /// <summary>
        /// Encerra o monitoramento da pasta de entrada
        /// </summary>
        public virtual void EndImport()
        {
            this.VerifyIsOpened();

            this.Adapter.EndReceive();
        }
        #endregion

        #region CancelFile
        /// <summary>
        /// Cancela a importação do arquivo
        /// </summary>
        public virtual void CancelFile()
        {
            this.VerifyIsOpened();

            this.Adapter.CancelStream();
        }
        #endregion

        #region RecordRead
        /// <summary>
        /// Evento disparado quando um registro é lido
        /// </summary>
        public event EventHandler<RecordEventArgs> RecordRead;

        /// <summary>
        /// Dispara evento RecordRead
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnRecordRead(RecordEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (RecordRead != null)
            {
                RecordRead(this, e);
            }
        }
        #endregion

        #region RecordReadError
        /// <summary>
        /// Evento disparado quando ocorre um erro ao ler um registro
        /// </summary>
        public event EventHandler<RecordReadErrorEventArgs> RecordReadError;

        /// <summary>
        /// Dispara o evento RecordReadError
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnRecordReadError(RecordReadErrorEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (RecordReadError != null)
            {
                RecordReadError(this, e);
            }
        }
        #endregion

        #region CloseProcess
        /// <summary>
        /// Fecha o processo de comunicação
        /// </summary>
        /// <param name="process">Nome do processo</param>
        protected override void CloseProcess()
        {
            base.CloseProcess();

            // Limpando processo
            this.Adapter.MessageReceived -= new EventHandler<MessageEventArgs>(Adapter_MessageReceived);
            this.Adapter.MessageReceivedError -= new EventHandler<MessageReceivedErrorEventArgs>(Adapter_MessageReceivedError);
            this.Adapter.StreamOpened -= new EventHandler<StreamOpenedEventArgs>(Adapter_StreamOpened);
            this.Adapter.StreamClosed -= new EventHandler<MessageEventArgs>(Adapter_StreamClosed);
            this.Adapter.StreamCanceled -= new EventHandler<MessageEventArgs>(Adapter_StreamCanceled);
            this.Adapter.NewFileCreated -= new EventHandler<FileCreatedEventArgs>(Adapter_NewFileCreated);
        }
        #endregion

		#region NewFileCreated
		/// <summary>
		/// Evento disparado quando um registro é lido
		/// </summary>
		public event EventHandler<FileCreatedEventArgs> NewFileCreated;

		/// <summary>
		/// Dispara evento RecordRead
		/// </summary>
		/// <param name="e">Argumento do evento</param>
		protected virtual void OnNewFileCreated(FileCreatedEventArgs e)
		{
			if (e == null)
				throw new ArgumentNullException("e");

			if (NewFileCreated != null)
			{
				NewFileCreated(this, e);
			}
		}
		#endregion
    }
}
